const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

// 页面跳转
const tranUrl = function (url) {
    wx.navigateTo({
        url: url
    })
}

// 获取openid
const getOpenid = function (app) {
    let openid = null;
    if (app.globalData.uOpenid) {
        openid = app.globalData.userInfo;
    } else {
        openid = wx.getStorageSync('uOpenid');
    }
    return openid;
}

// 显示tip层
let toast = obj => {
    var title = '提示';
    var icon = 'success';
    var duration = 2000;
    if (obj.title) {
        title = obj.title;
    }
    if (obj.icon) {
        icon = obj.icon;
    }
    if (obj.duration) {
        duration = obj.duration;
    }
    // "success", "loading", "none"
    wx.showToast({
        title: title,
        icon: icon,
        duration: duration,
        mask: true
    })
}

// 显示loading层
let loading = title => {
    var loadTitle = 'loading...';
    if (title) {
        loadTitle = title;
    }
    wx.showLoading({
        title: loadTitle,
        mask: true
    });
}

// 隐藏loading层
let hideLoad = function () {
    wx.hideLoading();
}

// 弹框
let tipBox = obj => {
    console.log(obj);
    let showCancel = true;
    if (obj.cancel == false) {
        showCancel = false;
    }
    wx.showModal({
        title: obj.title ? obj.title : '提示',
        content: obj.content,
        showCancel: showCancel,
        success: function (res) {
            if (res.confirm) {
                if (obj.sucFuc) {
                    obj.sucFuc(res);
                }                
            } else if (res.cancel) {
                if (obj.cancelFuc) {
                    obj.cancelFuc(res);
                }     
            }
        }
    })
}

// 更改顶部标题
let barTitle = title => {
    wx.setNavigationBarTitle({
        title: title
    })
}

// 分享转发
let shareApp = obj => {
    console.log(obj);
    if (obj.res.from === 'button') {
        // 来自页面内转发按钮
        console.log(obj.res.target)
    }
    return {
        title: 'sdfdf',
        path: obj.path,
        imageUrl: obj.imageUrl,
        success: function (res) {
            if (obj.sucFuc) {
                obj.sucFuc(res);
            }
        },
        fail: function (res) {
            if (obj.failFuc) {
                obj.failFuc(res);
            }
        }
    }
}

// 添加新数据到数组
let addNewToArr = function (orgArr, addFile) {
    for (let i = 0; i < addFile.length; i++) {
        orgArr.push(addFile[i]);
    }
    return orgArr;
}

// 检测是否为空
let checkIsNull = function (checkObj, showWord) {
    if (checkObj == '' || checkObj == null) {
        tipBox({title:'提示', content: showWord, cancel: false});
        return false;
    }
    return true;
}

// 检测二维数组是否重复
let checkIsUnique = function(orgArr) {
    let hash = {};
    let result = [];
    for (let i = 0, len = orgArr.length; i < len; i++) {
        if (!hash[orgArr[i]]) {
            result.push(orgArr[i]);
            hash[orgArr[i]] = true;
        }
    } 
    return result;
}

// 获取token
let getToken = function (app) {
    let token = wx.getStorageSync('token'), token_expire = wx.getStorageSync('token_expire'), nowTime = Date.now();
    console.log(token)
    if (token == '' || token == null) {
        wxLogin(app.globalData.host);
        token = wx.getStorageSync('token');
    } else if (token != '' && (nowTime - token_expire >= 0)) {
        wxLogin(app.globalData.host);
        token = wx.getStorageSync('token');
    }
    return token;
}

// 用户登陆
let wxLogin = function (host, fuc) {
    wx.login({
        success: ret => {
            if (ret.code) {
                // 发送 res.code 到后台换取 openId, sessionKey, unionId
                wx.request({
                    url: host + '/user/getOpenid',
                    data: {
                        code: ret.code
                    },
                    success: function (res) {
                        wx.setStorageSync('token', res.data.data.token);
                        wx.setStorageSync('token_expire', Date.now() + 7000000);
                        if (fuc) {
                            console.log('sdf');
                            fuc(0, res.data.data.token);
                        }
                    },
                    error: function (res) {
                        tipBox({ title: '提示', content: '网络不稳定，请稍后再试！', cancel: false });
                        console.log(res);
                    }
                })
            } else {
                tipBox({ title: '提示', content: '获取用户登录态失败！' + ret.errMsg, cancel: false });
                console.log('获取用户登录态失败！' + ret.errMsg);
            }
        }
    })
}

// 提示
let tips = (arg) => {
  wx.showToast({
    title: arg,
    icon: 'none'
  })
}

// 获取用户信息
let wxGetUserInfo = function (app) {
    wx.getUserInfo({
        success: res => {
            // 用户信息填充
            app.globalData.userInfo = res.userInfo;
            console.log(res.userInfo);
            var sendUserInfo = {
                token: getToken(app),
                nickname: res.userInfo.nickName,
                headimgurl: res.userInfo.avatarUrl,
                mobile: '',
                sex: res.userInfo.gender,
                country: res.userInfo.country,
                city: res.userInfo.city,
                language: res.userInfo.language,
            }
            wx.request({
                url: app.globalData.host + '/user/saveUserInfo',
                data: sendUserInfo,
                method: 'POST',
                header: {
                    "content-type": "application/x-www-form-urlencoded"
                },
                success: function (res) {
                    console.log(res);
                },
                error: function (res) {
                    tipBox({ title: '提示', content: '网络不稳定，请稍后再试！', cancel: false });
                    console.log(res);
                }
            })
            // 所以此处加入 callback 以防止这种情况
            if (app.userInfoReadyCallback) {
                app.userInfoReadyCallback(res);
            }
        }
    })
}

module.exports = {
    formatTime: formatTime,
    tranUrl: tranUrl,
    getOpenid: getOpenid,
    toast: toast,
    loading: loading,
    hideLoad: hideLoad,
    tipBox: tipBox,
    barTitle: barTitle,
    shareApp: shareApp,
    addNewToArr: addNewToArr,
    getToken: getToken,
    checkIsNull: checkIsNull,
    wxLogin: wxLogin,
    wxGetUserInfo: wxGetUserInfo,
    checkIsUnique: checkIsUnique,
    tips: tips
}
